package com.autumn.platform.core.xml;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.ParserConfigurationException;

import org.springframework.beans.factory.xml.DocumentLoader;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.XmlValidationModeDetector;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import com.autumn.platform.core.Defaults;
import com.autumn.platform.core.Utils;
import com.autumn.platform.core.logger.Logs;
import com.autumn.platform.core.spring.SpringHolder;
import com.autumn.platform.core.xml.context.IXmlParserContext;
import com.autumn.platform.core.xml.context.IXmlParserContextFactory;
import com.autumn.platform.core.xml.context.XmlValidationMode;

public class XmlHolder {

    private static final String PROFILE_ATTRIBUTE = "profile";

    private static final String MULTI_VALUE_ATTRIBUTE_DELIMITERS = ",; ";

    private static final XmlValidationModeDetector xmlValidationModeDetector = new XmlValidationModeDetector();

    public static IXmlParserContext getDefaultXmlParserContext() {
        IXmlParserContextFactory factory = Defaults.getDefaultComponent(IXmlParserContextFactory.class);
        return factory.newContext();
    }

    public static Document buildDocument(String location) {
        IXmlParserContext context = getDefaultXmlParserContext();
        return buildDocument(context, location);
    }

    public static Document buildDocument(IXmlParserContext context, String location) {
        Resource resource = null;
        File file = new File(location);
        if (file.exists()) {
            resource = new FileSystemResource(file);
        } else {
            try {
                resource = SpringHolder.getResource(location);
            } catch (IOException e) {
                throw new RuntimeException("load resource failure:" + location, e);
            }
        }
        return buildDocument(context, resource);
    }

    public static Document buildDocument(Resource resource) {
        IXmlParserContext context = getDefaultXmlParserContext();
        return buildDocument(context, resource);
    }

    public static Document buildDocument(IXmlParserContext context, Resource resource) {
        InputStream inputStream = null;
        try {
            int validationMode = detectValidationMode(context, resource);
            inputStream = resource.getInputStream();
            InputSource inputSource = new InputSource(inputStream);
            Document doc = buildDocument(context, inputSource, resource, validationMode);
            return doc;
        } catch (IOException ex) {
            throw new RuntimeException("IOException parsing XML document from " + resource.getDescription(), ex);
        } finally {
            Utils.closeQuietly(inputStream);
        }
    }

    /**
     * 根据名称获取相应子元素列表
     * 
     * @param ele 原始
     * @param childEleNames 子元素名称
     * @return 子元素名称与相应子元素列表构成的Map，若不存在子元素名称对应的元素，则该子元素名称对应空列表，但不会为null
     */
    public static Map<String, List<Element>> getChildElementsMapByTagName(Element ele, String... childEleNames) {
        Set<String> names = new HashSet<String>(Arrays.asList(childEleNames));
        Map<String, List<Element>> map = new HashMap<String, List<Element>>(names.size());
        for (String name : names) {
            map.put(name, new ArrayList<Element>());
        }
        NodeList nl = ele.getChildNodes();
        for (int i = 0, l = nl.getLength(); i < l; i++) {
            Node node = nl.item(i);
            if (node instanceof Element) {
                String name = getLocalName(node);
                if (names.contains(name)) {
                    map.get(name).add((Element) node);
                }
            }
        }
        return map;
    }

    /**
     * 根据名称获取子元素列表
     * 
     * @param ele 元素
     * @param childEleNames 子元素名称
     * @return 子元素列表
     */
    public static List<Element> getChildElementsByTagName(Element ele, String... childEleNames) {
        List<String> childEleNameList = Arrays.asList(childEleNames);
        NodeList nl = ele.getChildNodes();
        List<Element> childEles = new ArrayList<Element>();
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            if (node instanceof Element && nodeNameMatch(node, childEleNameList)) {
                childEles.add((Element) node);
            }
        }
        return childEles;
    }

    /**
     * 根据元素名获取子元素列表
     * 
     * @param ele 元素
     * @param childEleName 子元素名称
     * @return 子元素列表
     */
    public static List<Element> getChildElementsByTagName(Element ele, String childEleName) {
        return getChildElementsByTagName(ele, new String[] {childEleName});
    }

    /**
     * 根据元素名获取第一个子元素
     * 
     * @param ele 元素
     * @param childEleName 子元素名称
     * @return 子元素
     */
    public static Element getChildElementByTagName(Element ele, String childEleName) {
        NodeList nl = ele.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            if (node instanceof Element && nodeNameEquals(node, childEleName)) {
                return (Element) node;
            }
        }
        return null;
    }

    /**
     * 根据元素名获取第一个子元素的文本值
     * 
     * @param ele 元素
     * @param childEleName 子元素名称
     * @return 子元素文本值
     */
    public static String getChildElementValueByTagName(Element ele, String childEleName) {
        Element child = getChildElementByTagName(ele, childEleName);
        return (child != null ? getTextValue(child) : null);
    }

    /**
     * 获取所有子元素
     * 
     * @param ele 元素
     * @return 所有的直接子元素
     */
    public static List<Element> getChildElements(Element ele) {
        NodeList nl = ele.getChildNodes();
        List<Element> childEles = new ArrayList<Element>();
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            if (node instanceof Element) {
                childEles.add((Element) node);
            }
        }
        return childEles;
    }

    /**
     * 获取元素的文本值
     * 
     * @param valueEle 元素
     * @return 文本值
     */
    public static String getTextValue(Element valueEle) {
        StringBuilder sb = new StringBuilder();
        NodeList nl = valueEle.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node item = nl.item(i);
            if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) {
                sb.append(item.getNodeValue());
            }
        }
        return sb.toString();
    }

    /**
     * 获取节点的命名空间
     * 
     * @param node 节点
     * @return 命名空间
     */
    public static String getNamespaceURI(Node node) {
        return node.getNamespaceURI();
    }

    /**
     * 获取节点的本地节点名（去除命名空间前缀后的名称）
     * 
     * @param node 节点
     * @return 节点名称
     */
    public static String getLocalName(Node node) {
        String name = node.getLocalName();
        if (null == name) {
            name = node.getNodeName();
        }
        return name;
    }

    /**
     * 忽略命名空间的情况下，节点和名称是否匹配
     * 
     * @param node 节点
     * @param desiredName 期望的名称
     * @return 是否匹配
     */
    public static boolean nodeNameEquals(Node node, String desiredName) {
        return desiredName.equals(node.getNodeName()) || desiredName.equals(getLocalName(node));
    }

    /**
     * 忽略命名空间的情况下，节点名是否为预期名称的其中一个
     * 
     * @param node 节点
     * @param desiredNames 期望的名称
     * @return 是否匹配
     */
    public static boolean nodeNameMatch(Node node, Collection<String> desiredNames) {
        return (desiredNames.contains(node.getNodeName()) || desiredNames.contains(node.getLocalName()));
    }

    /**
     * 获取第一个子元素
     * 
     * @param ele 元素
     * @return 第一个直接子元素
     * @since 1.1.0
     */
    public static Element getChildElement(Element ele) {
        NodeList nl = ele.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            if (node instanceof Element) {
                return (Element) node;
            }
        }
        return null;
    }

    /**
     * 获取元素属性值
     * 
     * @param ele 元素
     * @param attr 属性名
     * @param defaultValue 默认值
     * @return 元素属性值
     * @since 1.1.0
     */
    public static String getAttribute(Element ele, String attr, String defaultValue) {
        String value = ele.getAttribute(attr);
        if (Utils.isBlank(value)) {
            value = defaultValue;
        } else {
            value = value.trim();
        }
        return value;
    }

    private static int detectValidationMode(IXmlParserContext context, Resource resource) {
        if (XmlValidationMode.AUTO.equals(context.getXmlValidationMode())) {//自动侦测
            if (resource instanceof InputStreamResource) {//不能多次读，就默认用Schema校验
                return XmlValidationModeDetector.VALIDATION_XSD;
            } else {
                InputStream inputStream = null;
                try {
                    inputStream = resource.getInputStream();
                    int validationMode = xmlValidationModeDetector.detectValidationMode(inputStream);
                    return validationMode;
                } catch (IOException ex) {
                    throw new RuntimeException("detect the validation mode of XML document from " + resource.getDescription(), ex);
                } finally {
                    Utils.closeQuietly(inputStream);
                }
            }
        } else {
            return context.getXmlValidationMode().getCode();
        }
    }

    /**
     * 执行解析，根据根元素的profile属性判断环境是否匹配，不匹配则终止解析
     * 
     * @param configuration
     * @param context
     * @param inputSource
     * @param resource
     */
    private static Document buildDocument(IXmlParserContext context, InputSource inputSource, Resource resource, int validationMode) {
        try {
            Document doc = doLoadDocument(context, inputSource, resource, validationMode);
            Element root = doc.getDocumentElement();
            Environment environment = extractEnvironment(context);

            String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
            if (null != environment && !Utils.isBlank(profileSpec)) {
                String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
                if (!environment.acceptsProfiles(specifiedProfiles)) {
                    Logs.info("Skipped XML file due to specified profiles [" + profileSpec + "] not matching: " + resource);
                    return null;
                }
            }
            Logs.info("load XML file : " + resource);
            return doc;
        } catch (SAXParseException ex) {
            throw new RuntimeException("Line " + ex.getLineNumber() + " in XML document from " + resource.getDescription() + " is invalid", ex);
        } catch (SAXException ex) {
            throw new RuntimeException("XML document from " + resource.getDescription() + " is invalid", ex);
        } catch (ParserConfigurationException ex) {
            throw new RuntimeException("Parser configuration exception parsing XML from " + resource.getDescription(), ex);
        } catch (IOException ex) {
            throw new RuntimeException("IOException parsing XML document from " + resource.getDescription(), ex);
        } catch (Throwable ex) {
            throw new RuntimeException("Unexpected exception parsing XML document from " + resource.getDescription(), ex);
        }
    }

    /**
     * 加载文档
     * 
     * @param context
     * @param inputSource
     * @param resource
     * @return
     * @throws Exception
     */
    private static Document doLoadDocument(IXmlParserContext context, InputSource inputSource, Resource resource, int validationMode) throws Exception {
        DocumentLoader loader = extractDocumentLoader(context);
        EntityResolver entityResolver = extractEntityResolver(context);
        ErrorHandler errorHandler = extractErrorHandler(context);
        // 如果是XSD，加载器会强制设置namespaceAware为true
        Document document = loader.loadDocument(inputSource, entityResolver, errorHandler, validationMode, true);
        return document;
    }

    private static Environment extractEnvironment(IXmlParserContext context) {
        Environment environment = context.getEnvironment();
        return environment;
    }

    private static ErrorHandler extractErrorHandler(IXmlParserContext context) {
        ErrorHandler errorHandler = context.getErrorHandler();
        return errorHandler;
    }

    private static EntityResolver extractEntityResolver(IXmlParserContext context) {
        EntityResolver entityResolver = context.getEntityResolver();
        return entityResolver;
    }

    private static DocumentLoader extractDocumentLoader(IXmlParserContext context) {
        return context.getDocumentLoader();
    }
}
